package com.gbei.center.interceptor;

import com.gbei.center.common.Constants;
import com.gbei.center.common.SpringContextUtils;
import com.gbei.center.oauth.mapper.AuthClientDetailsMapper;
import com.gbei.center.oauth.mapper.AuthClientScopeMapper;
import com.gbei.center.oauth.mapper.AuthClientUserMapper;
import com.gbei.center.oauth.mapper.AuthScopeMapper;
import com.gbei.center.utils.message.ResponseInfo;
import com.gbei.center.utils.message.Result;
import com.gbei.center.oauth.model.*;
import com.gbei.center.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 检查是否已经存在授权
 *
 */
public class OauthInterceptor extends HandlerInterceptorAdapter{
    @Autowired
    private AuthClientUserMapper authClientUserMapper;
    @Autowired
    private AuthClientDetailsMapper authClientDetailsMapper;
    @Autowired
    private AuthScopeMapper authScopeMapper;
    @Autowired
    private AuthClientScopeMapper authClientScopeMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //客户端ID
        String clientIdStr = request.getParameter("client_id");

        //回调URL
        String redirectUri = request.getParameter("redirect_uri");

        //校验参数
        if(!StringUtils.isNoneBlank(clientIdStr) || !StringUtils.isNoneBlank(redirectUri)){
            return this.generateErrorResponse(response, ResponseInfo.INVALID_REQUEST.messageToResult());
        }

        //1. 查询是否存在授权信息
        AuthClientDetails clientDetails = authClientDetailsMapper.selectByClientId(clientIdStr);

        if(clientDetails == null){
            return this.generateErrorResponse(response, ResponseInfo.INVALID_CLIENT.messageToResult());
        }

        if(!clientDetails.getRedirectUri().equals(redirectUri)){
            return this.generateErrorResponse(response, ResponseInfo.REDIRECT_URI_MISMATCH.messageToResult());
        }

        HttpSession session = request.getSession();
        //参数信息
        String params = "?redirectUri=" + SpringContextUtils.getRequestUrl(request);

        //获取session中存储的 user
        PlatformUser user = (PlatformUser) session.getAttribute(Constants.SESSION_USER);

        //根据clientId获取scope
        StringBuffer scopeStr = new StringBuffer();
        List<AuthClientScope> list = authClientScopeMapper.listAuthClientScope(clientDetails.getId());
        for (int i = 0; i < list.size(); i++) {
            AuthScope authScope = authScopeMapper.selectByPrimaryKey(list.get(i).getAuthScopeId());
            if (i == list.size() - 1){
                scopeStr.append(authScope.getScopeName());
            }else {
                scopeStr.append(authScope.getScopeName() + ",");
            }
        }
        String scope = scopeStr.toString();

        if(scope == null){
            return this.generateErrorResponse(response, ResponseInfo.INVALID_SCOPE.messageToResult());
        }

        params = params + "&client_id=" + clientIdStr + "&scope=" + scope;

        //2. 查询用户给接入的客户端是否已经授权
        AuthClientUser clientUser = authClientUserMapper.selectByClientId(clientDetails.getId(), user.getUserId());
        if(clientUser != null){
            return true;
        }else{
            //如果没有授权，则跳转到授权页面
            response.sendRedirect(request.getContextPath() + "/oauth2.0/authorizePage" + params);
            return false;
        }
    }
    
    /**
     * 组装错误请求的返回
     */
    /**
     * 组装错误请求的返回
     */
    private boolean generateErrorResponse(HttpServletResponse response, Result<?> result) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        response.getWriter().write(JsonUtils.toJson(result));
        return false;
    }

}
